package ar.com.ford.it.fullEconomics.logic;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Collection;
import ar.com.ford.it.fullEconomics.FullEconomicsPrs;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.persistence.dao.AgreementItemDao;
import ar.com.ford.it.fullEconomics.persistence.dao.CurrencyDao;
import ar.com.ford.it.fullEconomics.persistence.dao.VehiclelinDao;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesr03Agreement;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesr04Agreemitem;
import ar.com.ford.it.fullEconomics.persistence.dto.Teess01Supplier;
import ar.com.ford.it.fullEconomics.wslx.FullEconomicsWslxUser;
import ar.com.ford.it.webengine.persistence.PersistenceUtil;
import com.ford.it.logging.ILogger;
import com.ford.it.logging.Level;
import com.ford.it.logging.LogFactory;
import com.ford.it.persistence.PersistenceException;

public class AgreementItemLogic {
    private static final String CLASS_NAME = CommodityLogic.class.getName();
    private static final ILogger log = LogFactory.getInstance().getLogger(
            CLASS_NAME);

    /**
     * crea un nuevo item, debe contener el agreement al que pertenece
     * 
     * @param item
     * @param user
     * @throws FullEconomicsException
     */
    public void createAgreementItem(Teesr04Agreemitem item,
                                    FullEconomicsWslxUser user)
            throws FullEconomicsException {

        String METHOD_NAME = "createAgreementItem";
        log.entering(CLASS_NAME, METHOD_NAME);

        AgreementItemDao dao = new AgreementItemDao();
        String[] fields = new String[2];
        Object[] values = new Object[2];

        try {
            PersistenceUtil.newTransaction();
            Teesr04Agreemitem prevAgreemItem = this.findPrevAgreementItem(item);
            if (item.getEesr04AgritmIncrPercentP() != null) {
                if (prevAgreemItem != null) {
                    item.setEesr04AgritmIncrPercentP(item
                            .getEesr04AgritmNewpriceAmounA().subtract(
                                    prevAgreemItem
                                            .getEesr04AgritmNewpriceAmounA())
                            .divide(
                                    prevAgreemItem
                                            .getEesr04AgritmNewpriceAmounA(),
                                    5, BigDecimal.ROUND_HALF_EVEN));
                } else {
                    throw new FullEconomicsException(
                            new Exception(),
                            FullEconomicsPrs.MessageErrors.AgreementItem.NO_PREV_AGREEMENT);
                }
            } else {
                if (prevAgreemItem != null) {
                    item.setEesr04AgritmNewpriceAmounA(prevAgreemItem
                            .getEesr04AgritmNewpriceAmounA().multiply(
                                    new BigDecimal(1).add(item
                                            .getEesr04AgritmIncrPercentP()
                                            .divide(new BigDecimal(100)))));
                    item.setEesr04CurrencyCodeC(prevAgreemItem
                            .getEesr04CurrencyCodeC());
                }
            }
            fields[0] = "eesr04PlantCodeC";
            values[0] = user.getTeesg01Plant();
            fields[1] = "teesr03Agreement";
            values[1] = item.getTeesr03Agreement();
            Integer lastCode = dao.getMax(new Teesr04Agreemitem(), fields,
                    values, "eesr04AgritmNumberK");
            item.setEesr04AgritmNumberK(lastCode + 1);
            item.setEesr04PlantCodeC(user.getTeesg01Plant());
            item.setEesr04CreateS(new Timestamp(System.currentTimeMillis()));
            item.setEesr04CreateUserC(user.getId());
            item.setEesr04LastUpdtS(new Timestamp(System.currentTimeMillis()));
            item.setEesr04LastUpdtUserC(user.getId());
            dao.createAgreementItem(item);

            PersistenceUtil.commitTransaction();

        } catch (PersistenceException pe) {

            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "PersistenceException", pe);
            try {
                PersistenceUtil.rollbackTransaction();
            } catch (PersistenceException rollbackEx) {
                rollbackEx.printStackTrace();
            }

            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Create Request item Exception", pe);
            throw new FullEconomicsException(pe,
                    FullEconomicsPrs.MessageErrors.AgreementItem.CREATE);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    /**
     * Guarda los cambio hechos en el item
     * 
     * @param item
     * @param user
     * @throws FullEconomicsException
     */
    public void updateAgreementItem(Teesr04Agreemitem item,
                                    FullEconomicsWslxUser user)
            throws FullEconomicsException {

        String METHOD_NAME = "updateAgreementItem";
        log.entering(CLASS_NAME, METHOD_NAME);

        AgreementItemDao dao = new AgreementItemDao();
        VehiclelinDao lineDao = new VehiclelinDao();
        CurrencyDao currDao = new CurrencyDao();
        Teesr04Agreemitem workingCopy = null;

        try {
            PersistenceUtil.newTransaction();
            PersistenceUtil.getPersistenceManager().clearCache();
            Teesr04Agreemitem prevAgreemItem = this.findPrevAgreementItem(item);
            if (item.getEesr04AgritmIncrPercentP() != null) {
                if (prevAgreemItem != null) {
                    item.setEesr04AgritmIncrPercentP(item
                            .getEesr04AgritmNewpriceAmounA().subtract(
                                    prevAgreemItem
                                            .getEesr04AgritmNewpriceAmounA())
                            .divide(
                                    prevAgreemItem
                                            .getEesr04AgritmNewpriceAmounA(),
                                    5, BigDecimal.ROUND_HALF_EVEN));
                } else {
                    throw new FullEconomicsException(
                            new Exception(),
                            FullEconomicsPrs.MessageErrors.AgreementItem.NO_PREV_AGREEMENT);
                }
            } else {
                if (prevAgreemItem != null) {
                    item.setEesr04AgritmNewpriceAmounA(prevAgreemItem
                            .getEesr04AgritmNewpriceAmounA().multiply(
                                    new BigDecimal(1).add(item
                                            .getEesr04AgritmIncrPercentP()
                                            .divide(new BigDecimal(100)))));
                    item.setEesr04CurrencyCodeC(prevAgreemItem
                            .getEesr04CurrencyCodeC());
                }
            }
            workingCopy = dao.getAgreementItemForUpdate(item
                    .getTeesr03Agreement(), item.getEesr04AgritmNumberK(), user
                    .getTeesg01Plant());
            workingCopy.setEesr04AgritmEffectiveDateY(item
                    .getEesr04AgritmEffectiveDateY());
            workingCopy.setEesr04AgritmIncrPercentP(item
                    .getEesr04AgritmIncrPercentP());
            workingCopy.setEesr04AgritmNewpriceAmounA(item
                    .getEesr04AgritmNewpriceAmounA());
            workingCopy.setEesr04CurrencyCodeC(currDao
                    .getCurrencyForUpdate(item.getEesr04CurrencyCodeC()
                            .getEesm01CurrencyCodeC()));
            workingCopy.setEesr04CurrencyCodeC(null);
            workingCopy.setTeesf01Fulleconom(item.getTeesf01Fulleconom());
            if (item.getNcas012VehicleVw() != null) {
                workingCopy.setNcas012VehicleVw(lineDao
                        .getVehiclelinUpdateByPk(item.getNcas012VehicleVw()));
            } else
                workingCopy.setNcas012VehicleVw(null);
            workingCopy.setEesr04LastUpdtS(new Timestamp(System
                    .currentTimeMillis()));
            workingCopy.setEesr04LastUpdtUserC(user.getId());

            PersistenceUtil.commitTransaction();

        } catch (PersistenceException pe) {

            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "PersistenceException", pe);
            try {
                PersistenceUtil.rollbackTransaction();
            } catch (PersistenceException rollbackEx) {
                rollbackEx.printStackTrace();
            }

            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Update Request item Exception", pe);
            throw new FullEconomicsException(pe,
                    FullEconomicsPrs.MessageErrors.AgreementItem.UPDATE);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
    }

    /**
     * busca todos los items de un agreement
     * 
     * @param agreement
     * @return
     * @throws FullEconomicsException
     */
    public Collection<Teesr04Agreemitem> findAgreementItems(
                                                            Teesr03Agreement agreement)
            throws FullEconomicsException {
        String METHOD_NAME = "findAgreementItems";
        log.entering(CLASS_NAME, METHOD_NAME);
        Collection<Teesr04Agreemitem> items = null;
        AgreementItemDao dao = new AgreementItemDao();
        String[] fields = new String[2];
        Object[] values = new Object[2];

        try {
            fields[0] = "eesr04PlantCodeC";
            values[0] = agreement.getEesr03PlantCodeC();
            fields[1] = "teesr03Agreement";
            values[1] = agreement;

            items = dao.findAll(new Teesr04Agreemitem(), fields, values);
        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Find agreement items Exception", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.AgreementItem.FIND);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
        return items;

    }

    /**
     * busca todos los items de un agreement
     * 
     * @param agreement
     * @return
     * @throws FullEconomicsException
     */
    public Collection<Teesr04Agreemitem> agreementItemsHistory(
                                                               Teess01Supplier supplier)
            throws FullEconomicsException {
        String METHOD_NAME = "agreementItemsHistory";
        log.entering(CLASS_NAME, METHOD_NAME);
        Collection<Teesr04Agreemitem> items = null;
        AgreementItemDao dao = new AgreementItemDao();

        try {
            items = dao.findAgreementItemHistory(supplier);
        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Find agreement items Exception", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.AgreementItem.FIND);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
        return items;

    }

    /**
     * busca todos los items de un agreement
     * 
     * @param agreement
     * @return
     * @throws FullEconomicsException
     */
    public Teesr04Agreemitem findPrevAgreementItem(Teesr04Agreemitem agreemItem)
            throws FullEconomicsException {
        String METHOD_NAME = "findPrevAgreementItem";
        log.entering(CLASS_NAME, METHOD_NAME);
        Collection<Teesr04Agreemitem> items = null;
        Teesr04Agreemitem item = null;
        AgreementItemDao dao = new AgreementItemDao();

        try {
            items = dao.findPrevAgreementItems(agreemItem);
            if (items.isEmpty())
                item = null;
            else {
                item = items.iterator().next();
                for (Teesr04Agreemitem tempItem : items) {
                    if (item.getEesr04AgritmEffectiveDateY().getTime() < tempItem
                            .getEesr04AgritmEffectiveDateY().getTime())
                        item = tempItem;
                }
            }
        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Find agreement items Exception", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.AgreementItem.FIND);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
        return item;

    }

    /**
     * busca todos los items de un agreement ordenados por vehiclelin
     * 
     * @param agreement
     * @return
     * @throws FullEconomicsException
     */
    public Collection<Teesr04Agreemitem> findAgreementItemsOrderByVehicle(
                                                                          Teesr03Agreement agreement)
            throws FullEconomicsException {
        String METHOD_NAME = "findAgreementItems";
        log.entering(CLASS_NAME, METHOD_NAME);
        Collection<Teesr04Agreemitem> items = null;
        AgreementItemDao dao = new AgreementItemDao();

        try {
            items = dao.findAgreementItemsOrderByVehicle(agreement);
        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Find agreement items Exception", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.AgreementItem.FIND);
        }

        log.exiting(CLASS_NAME, METHOD_NAME);
        return items;

    }

    /**
     * borra el item
     * 
     * @param item
     * @throws FullEconomicsException
     */
    public void deleteAgreementItem(Teesr04Agreemitem item)
            throws FullEconomicsException {
        String METHOD_NAME = "deleteAgreementItem";
        log.entering(CLASS_NAME, METHOD_NAME);
        AgreementItemDao dao = new AgreementItemDao();
        try {
            PersistenceUtil.newTransaction();
            dao.deleteAgreementItem(item);
            PersistenceUtil.commitTransaction();
        } catch (PersistenceException e) {
            log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
                    "Find agreement items Exception", e);
            throw new FullEconomicsException(e,
                    FullEconomicsPrs.MessageErrors.AgreementItem.DELETE);
        }
        log.exiting(CLASS_NAME, METHOD_NAME);
    }

}
